package com.common.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseDao<T> {
	private static String driverClass="oracle.jdbc.OracleDriver";
	private String url="jdbc:oracle:thin:@localhost:1521:orcl";
	private String username="scott";
	private String password="tiger";
	
	static{
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected Connection getConnection(){
		try {
			return DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	protected void closeAll(Connection con,Statement sta,ResultSet rs){
		try {
			if(rs!=null) rs.close();
			if(sta!=null) sta.close();
			if(con!=null) con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	protected int executeUpdate(String sql,Object[] objs){
		Connection conn=this.getConnection();
		PreparedStatement prs=null;
		try {
			prs=conn.prepareStatement(sql);
			if(objs!=null && objs.length>0){
				for(int i=0;i<objs.length;i++){
					prs.setObject(i+1, objs[i]);
				}
			}
			return prs.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			this.closeAll(conn, prs, null);
		}
		return 0;
	}
	public abstract T getEntity(ResultSet rs);
	
	protected List<T> findBySql(String sql,Object[] obj){
		Connection conn = getConnection();
		List<T> list = new ArrayList<T>();
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			pst = conn.prepareStatement(sql);
			if(obj.length>0&&obj!=null)
				for(int i=0;i<obj.length;i++)
					pst.setObject(i+1,obj[i]);
			rs = pst.executeQuery();
			while(rs.next()){
				list.add(getEntity(rs));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			closeAll(conn, pst, rs);
		}
		return list;
	}
}
